//
//  MainTabBarViewController.m
//  YangDongXi
//
//  Created by windy on 15/4/8.
//  Copyright (c) 2015年 cocoa. All rights reserved.
//

#import "MainTabBarViewController.h"
//#import "LoadingPageViewController.h"
#import "UIViewController+MKExtension.h"
//#import "MKShoppingCartViewController.h"
//#import <PureLayout.h>
#import "AppDelegate.h"
#import "MKLoginViewController.h"
#import <NYXImagesKit.h>
//#import <UIAlertView+Blocks.h>
#import <AHKNavigationController.h>
#import "sys/utsname.h"

#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_RETINA ([[UIScreen mainScreen] scale] >= 2.0)

#define SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)
#define SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)
#define SCREEN_MAX_LENGTH (MAX(SCREEN_WIDTH, SCREEN_HEIGHT))
#define SCREEN_MIN_LENGTH (MIN(SCREEN_WIDTH, SCREEN_HEIGHT))

@interface MainTabBarViewController ()<UIAlertViewDelegate, UITabBarControllerDelegate>

//@property (nonatomic, strong) MKHomePageViewController *homePageViewController;

@property (nonatomic, strong) UITabBarItem *shoppingCartBarItem;
@property (nonatomic,strong)UILabel *labe;
@property (nonatomic, strong) NSString *appUrl;
@property (nonatomic,strong)NSMutableArray *tabArray;
@property (nonatomic,strong)NSMutableArray *buttonArray;
@property (nonatomic,strong)UILabel *lab;
@property (nonatomic,strong)UIButton *butt;

@property (nonatomic,strong)AHKNavigationController *homeNav;
@property (nonatomic,strong)UILabel *homeLabel;
@property (nonatomic,strong)AHKNavigationController *cfvcNav;
@property (nonatomic,strong)UILabel *cfvcNavLabel;
@property (nonatomic,strong)AHKNavigationController *cartNav;
@property (nonatomic,strong)UILabel *cartNavLabel;
@end


@implementation MainTabBarViewController

- (void)dealloc
{
    [getUserCenter.shoppingCartModel removeObserver:self forKeyPath:@"itemCount"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.delegate = self;
    self.tabArray = [NSMutableArray array];
    self.buttonArray = [NSMutableArray array];
    [self loadTabs];
    [self launchAction];
    [getUserCenter.shoppingCartModel addObserver:self forKeyPath:@"itemCount" options:NSKeyValueObservingOptionNew context:NULL];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateCartBadge) name:@"updatecartnums" object:nil];
}


//购物车商品数量
- (UILabel *)labe{
    if (!_labe) {
        self.labe = [[UILabel alloc]initWithFrame:CGRectMake(205, 5, 15, 15)];
        if (IS_IPHONE && SCREEN_MAX_LENGTH == 736.0) {
            _labe.frame =CGRectMake(265, 5, 15, 15);
        }
        if (IS_IPHONE && SCREEN_MAX_LENGTH == 667.0) {
            _labe.frame =CGRectMake(242, 5, 15, 15);
        }
        
        _labe.backgroundColor = [UIColor colorWithHex:CardColorT];
        _labe.textColor = [UIColor whiteColor];
        _labe.font = [UIFont systemFontOfSize:10];
        _labe.textAlignment = 1;
        _labe.layer.cornerRadius = 7.5f;
        _labe.layer.masksToBounds = YES;
    }
    return _labe;
}

//KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"itemCount"])
    {
        [self updateCartBadge];
    }
}
//首页
- (UILabel *)homeLabel{
    if (!_homeLabel) {
        self.homeLabel = [[UILabel alloc]init];
        _homeLabel.frame = CGRectMake(25, 33, 30, 12);
        if (IS_IPHONE && SCREEN_MAX_LENGTH == 667.0) {
            _homeLabel.frame =CGRectMake(32, 33, 30, 12);
        }
        if (IS_IPHONE && SCREEN_MAX_LENGTH == 736.0) {
            _homeLabel.frame =CGRectMake(36.5f, 33, 30, 12);
        }
        _homeLabel.font = [UIFont systemFontOfSize:11];
        _homeLabel.text = @"首页";
        _homeLabel.textAlignment = 1;
    }
    return _homeLabel;
}

//分类
- (UILabel *)cfvcNavLabel{
    if (!_cfvcNavLabel) {
        self.cfvcNavLabel = [[UILabel alloc]init];
        _cfvcNavLabel.frame = CGRectMake(104, 33, 30, 12);
        if (IS_IPHONE && SCREEN_MAX_LENGTH == 667.0) {
            _cfvcNavLabel.frame =CGRectMake(125, 33, 30, 12);
        }
        if (IS_IPHONE && SCREEN_MAX_LENGTH == 736.0) {
            _cfvcNavLabel.frame =CGRectMake(140, 33, 30, 12);
        }
        _cfvcNavLabel.font = [UIFont systemFontOfSize:11];
        _cfvcNavLabel.text = @"分类";
        _cfvcNavLabel.textAlignment = 1;
    }
    return _cfvcNavLabel;
}

//购物车
- (UILabel *)cartNavLabel{
    if (!_cartNavLabel) {
        self.cartNavLabel = [[UILabel alloc]init];
        _cartNavLabel.frame = CGRectMake(180, 33, 40, 12);
        if (IS_IPHONE && SCREEN_MAX_LENGTH == 667.0) {
            _cartNavLabel.frame =CGRectMake(215, 33, 40, 12);
        }
        if (IS_IPHONE && SCREEN_MAX_LENGTH == 736.0) {
            _cartNavLabel.frame =CGRectMake(240, 33, 40, 12);
        }
        _cartNavLabel.font = [UIFont systemFontOfSize:11];
        _cartNavLabel.text = @"购物车";
        _cartNavLabel.textAlignment = 1;
    }
    return _cartNavLabel;
}

//tabBar
- (void)loadTabs
{
    
    self.homePageViewController = [[MKHomePageViewController alloc] init];
    self.homeNav = [[AHKNavigationController alloc]
                                       initWithRootViewController:self.homePageViewController];
    _homeNav.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"首页" image:[UIImage imageNamed:@"tabbar_home_normal"]selectedImage:[UIImage imageNamed:@"tabbar_home_highlight"]];
//    _homeNav.title = @"\U0000e602";
//    [_homeNav.tabBarItem setTitleTextAttributes:@{ NSFontAttributeName:[UIFont fontWithName:@"iconfont" size:25] } forState:UIControlStateNormal];
    _homeNav.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -2);
//   self.homeLabel.textColor = [UIColor colorWithHex:CardColorT];
//    [self.tabBar addSubview:_homeLabel];


      MKClassificationViewController *cfvc = [[MKClassificationViewController alloc] init];
   self.cfvcNav = [[AHKNavigationController alloc] initWithRootViewController:cfvc];
 
    _cfvcNav.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"分类" image:[UIImage imageNamed:@"tabbar_classify_normal"]
                                               selectedImage:[UIImage imageNamed:@"tabbar_classify_highlight"]];
//    self.cfvcNav.title = @"\U0000e608";
//    [_cfvcNav.tabBarItem setTitleTextAttributes:@{ NSFontAttributeName:[UIFont fontWithName:@"iconfont" size:25] } forState:UIControlStateNormal];
//    self.cfvcNavLabel.textColor = [UIColor lightGrayColor];
//    [self.tabBar addSubview:_cfvcNavLabel];
    _cfvcNav.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -2);
//    self.cfvcNav.title = @"\U0000e608";
//    [_cfvcNav.tabBarItem setTitleTextAttributes:@{ NSFontAttributeName:[UIFont fontWithName:@"iconfont" size:25] } forState:UIControlStateNormal];
    MKShoppingCartViewController *cart = [MKShoppingCartViewController create];
    cart.hidesBottomBarWhenPushed = NO;
    self.cartNav = [[AHKNavigationController alloc] initWithRootViewController:cart];
    _cartNav.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"购物车" image:[UIImage imageNamed:@"tabbar_shoppingcart_normal"]
                                               selectedImage:[UIImage imageNamed:@"tabbar_shoppingcart_highlight"]];

    _cartNav.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -2);
    
    self.shoppingCartBarItem = _cartNav.tabBarItem;
    [self updateCartBadge];
    
    UserCenterViewController *uc = [UserCenterViewController create];
    AHKNavigationController *ucNav = [[AHKNavigationController alloc] initWithRootViewController:uc];
    ucNav.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"会员中心" image:[UIImage imageNamed:@"tabbar_mine_normal"]
                                             selectedImage:[UIImage imageNamed:@"tabbar_mine_highlight"]];
    ucNav.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -2);
    
    [self setViewControllers:@[_homeNav, _cfvcNav, _cartNav, ucNav]];
    [self.tabBar addSubview:self.labe];
}

- (void)launchAction
{
    if ([appDelegate.appConfig launchTimesThisVersion] <= 1)
    {
        //第一次启动
        [self firstLaunchAction];
    }
    else
    {
        //检测版本
        [self performSelector:@selector(checkVersion) withObject:nil afterDelay:0];
    }
}

//获取启动页
- (UIImage *)getLaunchImage
{
    NSDictionary *dict = @{@"640x960" : @"LaunchImage-700", @"640x1136" : @"LaunchImage-700-568h",
                           @"750x1334" : @"LaunchImage-800-667h", @"1242x2208" : @"LaunchImage-800-Portrait-736h"};
    
    NSString *key = [NSString stringWithFormat:@"%dx%d", (int)[appDelegate.appConfig screenResolution].width,
                     (int)[appDelegate.appConfig screenResolution].height];
    
    return [UIImage imageNamed:dict[key]];
}

//第一次启动时获取启动页
- (void)firstLaunchAction
{
    UIImageView *launchImg = [[UIImageView alloc] initWithImage:[self getLaunchImage]];
    launchImg.userInteractionEnabled = YES;
    launchImg.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:launchImg];
    [launchImg autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
    /* NSEC_PER_SEC 秒
     * NSEC_PER_MSEC 毫秒
     * NSEC_PER_USEC 微秒
     */
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^
    {
        //0.25秒后执行
        LoadingPageViewController *loadingVc = [LoadingPageViewController create];
        loadingVc.lanuchImage = [self getLaunchImage];
        
        [self presentViewController:loadingVc animated:NO completion:^
        {
            [launchImg removeFromSuperview];
        }];
    });
}

- (void)checkVersion
{
    [self checkVersionWithOutAlertIfLatest:YES CompletionHandler:NULL];
}

//版本更新
- (void)checkVersionWithOutAlertIfLatest:(BOOL)noAlertIfLatest CompletionHandler:(void (^)())handler
{
    NSString *t = [NSString stringWithFormat:@"%i", (int)[[NSDate date] timeIntervalSince1970]];
    [MKNetworking MKGETUrl:Updata paramters:@{@"x" : t}
                completion:^(MKHttpResponse *response)
    {
        if (response.errorMsg != nil)
        {
            return ;
        }
        NSDictionary *dict = response.mkResponseData[@"ios"];
        NSString *needNormalUpdate = dict[@"is_update"];
        NSString *isForceUupdate = dict[@"is_force_update"];
        NSString *newVersion = dict[@"version"];
        NSString *desc = dict[@"desc"];
        self.appUrl = dict[@"app_url"];
        if ([isForceUupdate isEqualToString:@"1"] && ![getAppConfig.getAppVersion isEqualToString:newVersion])
        {
            [UIAlertView showWithTitle:[NSString stringWithFormat:@"检测到新版本v%@", newVersion]
                               message:desc cancelButtonTitle:@"确认" otherButtonTitles:nil
                              tapBlock:^(UIAlertView * __nonnull alertView, NSInteger buttonIndex)
            {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.appUrl]];
                dispatch_async(dispatch_get_main_queue(), ^
                {
                    exit(0);
                });
            }];
            return;
        }
        if (![needNormalUpdate isEqualToString:@"1"])
        {
            return;
        }
        if ([getAppConfig.getAppVersion isEqualToString:newVersion])
        {
            return;
        }
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"检测到新版本v%@", newVersion]
                                                            message:desc delegate:self cancelButtonTitle:@"残忍地拒绝"
                                                  otherButtonTitles:@"快乐地升级", nil];
        [alertView show];
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.appUrl]];
    }
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController
shouldSelectViewController:(UIViewController *)viewController
{
//    if (viewController.tabBarItem == self.homeNav.tabBarItem) {
//        _homeNav.title = @"\U0000e602";
//        self.homeLabel.textColor = [UIColor colorWithHex:CardColorT];
//
//    }else{
//        _homeNav.title = @"\U0000e60a";
//        self.homeLabel.textColor = [UIColor lightGrayColor];
//    }
//    if (viewController.tabBarItem == self.cfvcNav.tabBarItem) {
//        _cfvcNav.title = @"\U0000e601";
//        self.cfvcNavLabel.textColor = [UIColor colorWithHex:CardColorT];
//        
//    }else{
//        _cfvcNav.title = @"\U0000e608";
//       self.cfvcNavLabel.textColor = [UIColor lightGrayColor];
//    }
//    if (viewController.tabBarItem == self.cartNav.tabBarItem) {
//       self.cartNav.title = @"\U0000e600";
//        self.cartNavLabel.textColor = [UIColor colorWithHex:CardColorT];
//        
//    }else{
//        _cartNav.title = @"\U0000e605";
//        self.cartNavLabel.textColor = [UIColor lightGrayColor];
//    }
    
//    viewController.tabBarItem setTitle:<#(NSString *)#>
    return [self checkTabNeedLoginWithShouldSelectViewController:viewController];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
//    [self.butt setTitleColor:[UIColor colorWithHex:CardColorT] forState:(UIControlStateNormal)];
//    [self.lab setTextColor:[UIColor colorWithHex:CardColorT]];
    
}

//购物车和我的页面进入时需要判断是否处于登录状态
- (BOOL)checkTabNeedLoginWithShouldSelectViewController:(UIViewController *)viewController
{
    UINavigationController *nv = (UINavigationController *)viewController;
    if (![nv.viewControllers[0] isKindOfClass:[UserCenterViewController class]] &&
        ![nv.viewControllers[0] isKindOfClass:[MKShoppingCartViewController class]])
    {
        return YES;
    }
    
    //MKAccountInfo *accountInfo = getUserCenter.accountInfo;
    NSString * accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    if (accessToken.length > 0)
    {
        return YES;
    }
    
    MKLoginViewController *lg = [MKLoginViewController create];
    //登录成功回调
    lg.successBlock = ^
    {
        if ([nv.viewControllers[0] isKindOfClass:[UserCenterViewController class]]) {
            [self selectTab:[UserCenterViewController class]];
        }
        if ([nv.viewControllers[0] isKindOfClass:[MKShoppingCartViewController class]]) {
            [self selectTab:[MKShoppingCartViewController class]];
        }
    };
   
    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:lg]
                       animated:YES completion:nil];
    return NO;
}

- (void)selectTab:(Class)tabClass
{
    for (UINavigationController *vc in self.viewControllers)
    {
        if (![vc.viewControllers[0] isKindOfClass:tabClass])
        {
            continue;
        }
        UINavigationController *nv = (UINavigationController *)self.selectedViewController;
        [nv popToRootViewControllerAnimated:self.selectedViewController == vc];
        if ([self checkTabNeedLoginWithShouldSelectViewController:vc])
        {
            self.selectedViewController = vc;
        }
        return;
    }
}

- (void)guideToOrderDetailWithOrderStatus:(MKOrderStatus)status{
    [self selectTab:[UserCenterViewController class]];
    dispatch_async(dispatch_get_main_queue(), ^
                   {
                       UINavigationController *nv = (UINavigationController *)self.selectedViewController;
                       MKOrdersViewController *olv = [MKOrdersViewController create];
                       olv.orderStatus = status;
                       [nv pushViewController:olv animated:YES];
                       
                   });
}

- (void)guideToOrderDetailWithOrderUid:(NSString *)orderUid throughOrderStatus:(MKOrderStatus)status
{
    [self selectTab:[UserCenterViewController class]];
    dispatch_async(dispatch_get_main_queue(), ^
    {
        UINavigationController *nv = (UINavigationController *)self.selectedViewController;
        MKOrdersViewController *olv = [MKOrdersViewController create];
        olv.orderStatus = status;
        [nv pushViewController:olv animated:NO];
        dispatch_async(dispatch_get_main_queue(), ^
        {
            MKOrderDetailViewController *odv = [[MKOrderDetailViewController alloc] init];
            odv.orderUid = orderUid;
            [nv pushViewController:odv animated:YES];
         
        });
    });
}
//回到首页
- (void)guideToHome
{
    self.tabBarController.tabBar.hidden = NO;
    [self selectTab:[MKHomePageViewController class]];
    [self.homePageViewController closeSearchView];
    
   
}

-(void)guideToHomeViewController:(UIViewController *)vc
{
    //所在页面不为首页的时候，先让它回到导航控制器的rootViewController，然后再设置选中为首页
    if (![vc isKindOfClass:[MKHomePageViewController class]] ) {
        //[vc.navigationController popToRootViewControllerAnimated:YES];
        [vc.navigationController popToViewController:vc.navigationController.viewControllers[0] animated:YES];
    }
    
    [self guideToHome];
    
    //[self selectTab:[MKHomePageViewController class]];
}

//回到购物车

-(void)guideToShoppingCart
{
    [self selectTab:[MKShoppingCartViewController class]];
}
  
//购物车是否为空，if判断
- (void)updateCartBadge
{
    NSInteger count = getUserCenter.shoppingCartModel.itemCount;
    MKAccountInfo *accountInfo = getUserCenter.accountInfo;
    if (count > 0 && accountInfo.accessToken.length > 0)
    {
//        self.shoppingCartBarItem.badgeValue = [NSString stringWithFormat:@"%li", (long)count];
        self.labe.hidden = NO;
        self.labe.text = [NSString stringWithFormat:@"%ld",count];
    }
    else
    {
//        self.shoppingCartBarItem.badgeValue = nil;
        self.labe.hidden = YES;
    }
}

//- (NSString*)deviceString
//{
//    // 需要#import "sys/utsname.h"
//    struct utsname systemInfo;
//    uname(&systemInfo);
//    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
//    
//    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
//    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
//    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
//    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
//    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
//    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
//    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
//    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
//    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
//    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
//    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
//    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
//    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
//    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
//    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
//    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
//    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
//    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
//    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
//    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
//    return deviceString;
//}

@end
